<template>
    <JwChat-index
      :config="config"
      :showRightBox="true"
      scrollType="noroll"
      :taleList="taleList"
      @enter="bindEnter"
      @clickTalk="talkEvent"
      v-model="inputMsg"
      :toolConfig="tool"
      :winBarConfig="winBarConfig"
    >
      <JwChat-talk :Talelist="talks" :config="quickConfig" @event="bindTalk" />
    </JwChat-index>
</template>

<script>
import { getUploadToken } from "@/api/monitor/file";
import {
  getHistory,
  getUser,
  getHistoryLimit,
  listReply,
  addReply,
  removeReply,
} from "@/api/customer/customerService";
import { getUserProfile } from "@/api/system/user";
import axios from "axios";
export default {
  name: "chat",
  data() {
    return {
      number: 0,
      size: 0,
      token: this.$store.state.user.token, //发送的后台token
      userId: 0,
      path: "wss://console.yooruan.com/chat", //发送地址
      socket: "",
      ID: "", // 客户uid
      uploadImgUrl: "http://upload-z2.qiniup.com",
      upload_domain: "",
      uploadData: {
        token: "",
        key: "",
      },
      quickConfig: {
        nav: ["快捷回复"],
        showAdd: true,
        maxlength: 20,
        showHeader: true,
        showDeleteBtn: true,
      },
      talks: [],
      title: "",
      openR: false,
      isShow: true,
      js: null,
      uids: 53,
      inputMsg: "",
      selectedData: [],
      taleList: [],
      tool: {
        show: ["img"],
        // show: ['file', 'history', 'img', ['文件1', '', '美图']],
        // showEmoji: false,
        callback: this.toolEvent,
      },
      config: {
        img: "",
        name: "",
        dept: "",
        callback: this.bindCover,
        historyConfig: {
          show: true,
          tip: "加载更多",
          callback: this.bindLoadHistory,
        },
      },
      winBarConfig: {
        active: "",
        width: "150px",
        listHeight: "60px",
        list: [],
        callback: this.bindWinBar,
      },
      listData: null,
      imgStr: "",
      intervalId: null,
    };
  },
  created() {
    this.init();
    this.getUserData();
    getUserProfile().then((response) => {
      this.userId = response.data.userId;
    });
    this.getTalk();
    this.dataRefreh();
  },
  // destroyed() {
  //   console.log(1);

  // },
  methods: {
    // 定时刷新数据函数
    dataRefreh() {
      // 计时器正在进行中，退出函数
      if (this.intervalId != null) {
        return;
      }
      // 计时器为空，操作
      this.intervalId = setInterval(() => {
        this.sdel();
      }, 15000);
    },
    // 停止定时器
    clear() {
      clearInterval(this.intervalId); //清除计时器
      this.intervalId = null; //设置为null
    },

    sdel() {
      if (this.token != "") {
        if (this.socket.readyState === this.socket.CLOSED) {
          this.$message.error("服务器断开连接！请刷新页面重试");
        } else {
          this.socket.send(
            "{'token':'" +
              this.token +
              "','fromRole': 'cs', 'action':'login_req' }"
          );
        }
      }
    },
    getTalk() {
      listReply().then((response) => {
        this.listData = response.rows;
        this.listData.forEach((element) => {
          this.talks.push(element.replyText);
        });
      });
    },
    getUserData() {
      getUser().then((response) => {
        this.ID = response.data.active;
        this.number = 10;
        let datas = { uid: this.ID, number: this.number, size: this.size };
        this.winBarConfig.active = response.data.active;
        this.winBarConfig.list = response.data.list;
        response.data.list.forEach((i) => {
          if (i.id == response.data.active) {
            this.config.name=i.name
            this.config.dept=i.dept
            this.config.img=i.img
          }
        });
        getHistoryLimit(datas).then((response) => {
          this.taleList = response.data;
        });
      });
    },
    talkEvent() {
      console.log(1);
    },
    /**
     * @description:
     * @param {*} type 当前点击的按钮
     * @param {*} plyload 附加文件或者需要处理的数据
     * @return {*}
     */
    toolEvent(type, plyload) {
      if (type == "history") {
        getHistory(this.ID).then((response) => {
          this.taleList = response.data;
        });
      }
      if (plyload != undefined && type == "img") {
        this.file = plyload[0];
        return new Promise((resolve, reject) => {
          getUploadToken()
            .then((response) => {
              this.uploadData.key = response.data.key;
              this.uploadData.token = response.data.token;
              this.upload_domain = response.data.domain;
              let data = new FormData();
              data.append("token", this.uploadData.token);
              data.append("file", this.file);
              axios({
                method: "POST",
                url: this.uploadImgUrl,
                data: data,
                timeout: 30000,
              })
                .then((data) => {
                  let url = this.upload_domain + data.data.key;
                  if (data.data.key) {
                    if (this.ID == "") {
                      this.$message.error("请选择聊天对象！");
                      return false;
                    }
                    this.socket.send(
                      "{'action':'send_msg_req', 'fromRole': 'cs', 'toRole':'customer', 'toUserId':" +
                        this.ID +
                        ", 'message': { 'bodyType': 'image', 'messageContent': '" +
                        url +
                        "' },'token':'" +
                        this.token +
                        "'}"
                    );
                  } else {
                    this.$message.error("上传失败");
                  }
                })
                .catch(function (err) {
                  this.$message.error("上传失败");
                });
              resolve(true);
            })
            .catch((err) => {
              console.log("出错了...", err);
              reject(false);
            });
        });
      }
    },

    /**
     * @description: 点击加载更多的回调函数
     * @param {*}
     * @return {*}
     */
    bindLoadHistory() {
      this.number = 10;
      this.size += 10;
      let datas = { uid: this.ID, number: this.number, size: this.size };
      if (this.ID) {
        debugger
        getHistoryLimit(datas).then((response) => {
          let list = response.data.concat(this.taleList);
          this.taleList = list;
        });
      }
    },
    bindCover(type) {
      console.log("header", type);
    },
    bindWinBar(play = {}) {
      play.data.readNum = 0;
      const { type, data = {} } = play;
      this.ID = data.id;
      this.config.name = data.name;
      this.config.dept = data.dept;
      this.config.img = data.img;
      this.number = 10;
      let datas = { uid: this.ID, number: this.number, size: this.size };
      debugger
      getHistoryLimit(datas).then((response) => {
        this.taleList = response.data;
      });
      if (type === "winBar") {
        const { id, dept, name, img } = data;
        this.winBarConfig.active = id;
      }
    },
    bindTalk(play) {
      if (play.key == "addTalk") {
        this.isvalue = true
        this.islength = true
        let data = { replyText: play.value };
        if (play.value == "") {
        this.$message.error("添加内容不能为空！");
        return false;
        }
        for (let i = 0; i < this.talks.length; i++) {
          if(this.talks[i]==play.value){
            this.$message.error("添加内容重复，请重新添加");
            this.isvalue = false
          }
        }
        if(this.talks.length + 1>10) {
          this.islength = false
          this.$message.error("快捷回复的数量超出限制");
        }else {
          this.islength = true
        }

        if(this.isvalue&&this.islength) {
          addReply(data).then((response) => {
            this.talks.push(play.value);
            this.listData.push(data);
            this.$message({
          message: '添加成功',
          type: 'success'
        });

        });
        }
      }
      if (play.key == "select") {
        this.inputMsg = play.value;
      }
      if (play.key == "delIndex") {
        removeReply(this.listData[play.value].replyText).then((response) => {
          this.talks.splice(play.value, 1);
          this.$message({
          message: '删除成功',
          type: 'success'
        });
        });
      }
    },
    // 发送消息
    bindEnter() {
      if (this.inputMsg == "") {
        this.$message.error("消息不能为空！");
        return false;
      }
      if (this.ID == "") {
        this.$message.error("请选择聊天对象！");
        return false;
      }
      let role = "customer";
      this.socket.send(
        "{'action':'send_msg_req', 'fromRole': 'cs', 'toRole':'customer', 'toUserId':" +
          this.ID +
          ", 'message': { 'bodyType': 'text', 'messageContent': '" +
          this.inputMsg +
          "' },'token':'" +
          this.token +
          "'}"
      );
    },
    init: function () {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function () {
      console.log("socket连接成功");
    },
    error: function () {
      console.log("连接错误");
    },
    getMessage: function (msg) {
      let sobj = msg.data;
      let objs = "";
      if (sobj) {
        objs = JSON.parse(sobj);
      }
      console.log(sobj);
      if (objs.action == "send_msg_resp") {
        //发送消息返回
        if (objs.result) {
          this.size = 0
          let datas = { uid: this.ID, number: this.number, size: this.size };
          debugger
          getHistoryLimit(datas).then((response) => {
            this.taleList = response.data;
            this.getUserData()
          });
        } else {
          this.$message.error("发送失败！");
        }
      } else if (objs.action == "receive_msg_notify") {
        // 接收消息返回
        getUser().then((response) => {
          this.winBarConfig.list = response.data.list;
        });
        this.size = 0
        let datas = { uid: this.ID, number: this.number, size: this.size };
        debugger
        getHistoryLimit(datas).then((response) => {
          this.taleList = response.data;
        });
      } else if (objs.action == "login_resp") {
        // 登录返回
      }
    },
    send: function () {
      this.socket.send(params);
    },
    close: function () {
      console.log("socket已经关闭");
    },
  },
  destroyed() {
    // 在页面销毁后，清除计时器
    this.clear();
    // 销毁监听
    this.socket.onclose = this.close;
  },
};
</script>
<style>
.item .info {
  margin-bottom: 5px;
}
.el-badge__content.is-fixed {
  position: absolute;
  top: 5px;
  right: -68px;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  font-size: 10px;
  text-align: center;
  padding: 0 1px 0 0px;
}

.el-row {
  font-size: 14px;
}
</style>
